import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {path: '/', redirect: '/home'},
  {path: '/layout', name: 'layout', component: import('../views/layout/index.vue'),children:[
    {path: '/home', name: 'home', component: import('../views/layout/home.vue')},
    {path: '/category', name: 'category', component: import('../views/layout/category.vue')},
    {path: '/cart', name: 'cart', component: import('../views/layout/cart.vue')},
    {path: '/my', name: 'my', component: import('../views/layout/my.vue')},
  ]},
  {path: '/search', name: 'search', component: import('../views/search/index.vue')},
  {path: '/searchlist', name: 'searchlist', component: import('../views/search/searchlist.vue')},
  {path: '/login', name: 'login', component: import('../views/login/index.vue')},
  {path: '/myorder', name: 'myorder', component: import('../views/myorder/index.vue')},
  {path: '/pay', name: 'pay', component: import('../views/pay/index.vue')},
  {path: '/prodetail/:id', name: 'prodetail', component: import('../views/prodetail/index.vue')},
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})


// 拦截路径
const authRoutes = ['pay', 'myorder']

/**
 * 导航守卫
 * @param to    去哪
 * @param from  从哪来
 * @param next  下一步
 */
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  if(!authRoutes.includes(to.path)){
    // 非拦截页面
    next()
  }

  // 拦截页面 判断token
  if(userStore.getToken){
    next()
  }else{
    next({path: '/login'})
  }
  
})

export default router
